package com.zf.zffencheng.exception;

import ch.qos.logback.classic.pattern.MarkerConverter;
import com.zf.zffencheng.model.Result;
import lombok.extern.log4j.Log4j2;
import org.slf4j.Marker;
import org.slf4j.helpers.BasicMarker;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Arrays;
import java.util.Optional;

/**
 * ClassName: AllExceptionHandler <br/>
 * Description:  <br/>
 * date: 2021/5/10 15:44<br/>
 *
 * @author william <br/>
 */
@RestControllerAdvice
@Log4j2
public class AllExceptionHandler {
    @ExceptionHandler(value =NullPointerException.class)
    public Result exceptionHandler(NullPointerException e){
        log.error("空指针：", e);
        return Result.error( Error_.DATA_EMPTY);
    }

    @ExceptionHandler(value =ResultException.class)
    public Result exceptionHandler(ResultException e){
        locationError(e, e.getMsg());
        log.warn("逻辑错误 code:{}, ：{}",e.getCode(),  e.getMsg());
        return Result.error(e);
    }

    @ExceptionHandler(value = MissingServletRequestParameterException.class)
    public Result exceptionHandler(MissingServletRequestParameterException e){
        locationError(e, e.getMessage());
        log.info("缺少必填参数：{}", e.getParameterName());
        return Result.error(String.format("缺少必填参数:%s", e.getParameterName()));
    }

   private void  locationError(Exception e, String msg){
       StackTraceElement[] stackTrace = e.getStackTrace();
       Optional<StackTraceElement> first = Arrays.stream(stackTrace).findFirst();
       boolean present = first.isPresent();
       if(present){
           StackTraceElement stackTraceElement = first.get();
           log.warn("错误:{}， 定位：{}", msg, stackTraceElement);
       }
    }
}
